from PySide6.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply
from PySide6.QtCore import QObject, QUrl, Signal, Slot, QIODevice, QByteArray

import requests
import json
import base64


class httpRequest(QObject):
    finished = Signal(QNetworkReply)
    host = "http://192.168.31.211:8000"

    def __init__(self):
        super().__init__()
        self.manager = QNetworkAccessManager()
        self.manager.finished.connect(self.on_finished)

    @Slot()
    def hasQrCode(self):
        """获取登录二维码"""
        url = "/api/wxCode/"
        data = {}
        request = QNetworkRequest(QUrl(self.host + url))
        self.manager.post(request, str(data).encode("utf-8"))
        print("发起请求...")

    @Slot(QNetworkReply)
    def on_finished(self, reply: QNetworkReply):
        # if reply.error() == QNetworkReply.NoError:
        #     print("Response:", reply.readAll().decode())
        # else:
        #     print("Error:", reply.errorString())
        self.finished.emit(reply)


from requests.packages.urllib3.exceptions import InsecureRequestWarning

# 禁用安全请求警告
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)


class myHttpRequest(requests.Session):
    """网络请求类"""

    finished = Signal(int, dict)

    def __init__(self):
        super().__init__()
        # self.host = "http://192.168.31.211:8000"
        self.host = "http://lease.3vppt.com"

    def do_get(self, url="", headers=None, params=None, data=None):
        url = self.host + url
        try:
            r = self.get(url, headers=headers, params=params, data=data, verify=False)
            return r.json() if r and r.status_code == 200 else None
        except BaseException as err:
            return None

    def do_post(self, url="", headers=None, params=None, data=None, json=None):
        url = self.host + url
        try:
            r = self.post(
                url, headers=headers, params=params, data=data, json=json, verify=False
            )
            return r.json() if r and r.status_code == 200 else None
        except BaseException as err:
            print(err)
            return None

    def hasQrCode(self):
        """获取登录二维码"""
        url = "/api/wxCode/"
        headers = {"Content-Type": "application/json"}
        res = self.do_post(url, headers=headers)
        return res

    def hasWxToken(self, state):
        """获取token"""
        url = "/api/waitToken/"
        headers = {"Content-Type": "application/json"}
        data = {"state": state}
        data = json.dumps(data, ensure_ascii=False).encode("utf8")
        res = self.do_post(url, headers=headers, data=data)
        return res

    def hasWxUserInfo(self, token):
        """获取用户信息"""
        url = "/api/Selfinfo/"
        headers = {"Content-Type": "application/json"}
        headers["Authorization"] = token
        res = self.do_post(url, headers=headers)
        return res

    def hasQiniuToken(self, token):
        """获取七牛token"""
        url = "/file/QiniuUpToken/"
        headers = {"Content-Type": "application/json"}
        headers["Authorization"] = token
        res = self.do_post(url, headers=headers)
        return res

    def hasQiniuMysql(self, token, header):
        """获取七牛本地存储"""
        b64c = self.toBase64Code()
        print(type(b64c))
        url = "/file/QiniuUpload/"
        headers = {"Content-Type": "application/json"}
        headers["Authorization"] = token
        data = {"header": header, "cover": b64c}
        data = json.dumps(data, ensure_ascii=False).encode("utf8")
        res = self.do_post(url, headers=headers, data=data)
        return res

    def hasWxTasks(self, token):
        """获取任务列表"""
        url = "/api/wyTask/"
        headers = {"Content-Type": "application/json"}
        headers["Authorization"] = token
        res = self.do_post(url, headers=headers)
        return res

    def toBase64Code(self):
        """将图片转换为base64编码"""
        with open("myimage.png", "rb") as fs:
            image_data = fs.read()
            base64_data = base64.b64encode(image_data)
        return base64_data.decode("utf8")
